package com.example.monitor.service.impl;

import com.example.monitor.exception.BusinessException;
import com.example.monitor.exception.NotFoundException;
import com.example.monitor.model.DO.AlarmRecord;
import com.example.monitor.model.DO.Worker;
import com.example.monitor.model.DTO.AlarmQueryDTO;
import com.example.monitor.model.DTO.AlarmRecordCreateDTO;
import com.example.monitor.model.DTO.AlarmStatusUpdateDTO;
import com.example.monitor.model.VO.AlarmRecordVO;
import com.example.monitor.model.VO.PageResult;
import com.example.monitor.model.enums.AlarmStatus;
import com.example.monitor.repository.AlarmRecordRepository;
import com.example.monitor.repository.WorkerRepository;
import com.example.monitor.service.AlarmService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Arrays;

@Service
@RequiredArgsConstructor
public class AlarmServiceImpl implements AlarmService {

    private final AlarmRecordRepository alarmRecordRepository;
    private final WorkerRepository workerRepository;

    @Override
    public PageResult<AlarmRecordVO> queryAlarmRecords(AlarmQueryDTO queryDTO) {
        // 转换时间
        Timestamp startTime = queryDTO.getStartTime() != null ?
                Timestamp.valueOf(queryDTO.getStartTime()) : null;
        Timestamp endTime = queryDTO.getEndTime() != null ?
                Timestamp.valueOf(queryDTO.getEndTime()) : null;

        Page<AlarmRecordVO> page = alarmRecordRepository.findAlarmRecordsAsVO(
                queryDTO.getAlarmType(),
                queryDTO.getWorkshop(),
                queryDTO.getStatus(),
                startTime,
                endTime,
                PageRequest.of(queryDTO.getPage()-1, queryDTO.getPageSize())
        );
        return new PageResult<>(page.getTotalElements(), page.getContent());
    }

    @Override
    @Transactional
    public void updateAlarmStatus(Long alarmId, AlarmStatusUpdateDTO updateDTO) {
        // 验证枚举值
        AlarmStatus status;
        try {
            status = AlarmStatus.fromCode(updateDTO.getStatus());
            //status = AlarmStatus.valueOf(updateDTO.getStatus().toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new BusinessException("无效的状态值: " + updateDTO.getStatus() +
                    "，有效值为: " + Arrays.toString(AlarmStatus.values()));
        }
        AlarmRecord alarmRecord = alarmRecordRepository.findById(alarmId)
                .orElseThrow(() -> new NotFoundException("报警记录不存在"));

        // 更新状态
        alarmRecord.setStatus(status);

        // 保存更新
        alarmRecordRepository.save(alarmRecord);
    }

    @Override
    @Transactional
    public Long addAlarmRecord(AlarmRecordCreateDTO alarmRecordCreateDTO) {
        AlarmRecord alarmRecord = new AlarmRecord();

        // 设置基本属性
        alarmRecord.setWorkshop(alarmRecordCreateDTO.getWorkshop());
        alarmRecord.setAlarmType(alarmRecordCreateDTO.getAlarmType());
        alarmRecord.setAlarmTime(alarmRecordCreateDTO.getAlarmTime());
        alarmRecord.setStatus(alarmRecordCreateDTO.getStatus() != null ?
                alarmRecordCreateDTO.getStatus() : AlarmStatus.unprocessed);
        alarmRecord.setImageUrl(alarmRecordCreateDTO.getThumbnailUrl());

        // 处理员工信息 - 使用 getReferenceById 避免立即查询
        if (alarmRecordCreateDTO.getWorkerId() != null && !alarmRecordCreateDTO.getWorkerId().isEmpty()) {
            Worker worker = workerRepository.getReferenceById(alarmRecordCreateDTO.getWorkerId());
            alarmRecord.setWorker(worker); // 这里只是设置代理对象，不会立即查询
        }

        // 保存记录
        AlarmRecord savedRecord = alarmRecordRepository.save(alarmRecord);
        return savedRecord.getAlarmId();
    }

    @Override
    @Transactional
    public void deleteAlarmRecord(Long alarmId) {
        // 检查记录是否存在
        AlarmRecord alarmRecord = alarmRecordRepository.findByAlarmId(alarmId)
                .orElseThrow(() -> new NotFoundException("报警记录不存在"));

        // 删除记录
        alarmRecordRepository.delete(alarmRecord);
    }
}